package com.ltw.dreamer.common.util;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

public class VerticalTableUtil {
	public static final Logger LOGGER = Logger.getLogger(VerticalTableUtil.class);
	
	public static void invokePropertySetter(Object instance, String value, int index) {
		try {
			Method setter = instance.getClass().getDeclaredMethod("setIndex" + index, Double.class);
			setter.invoke(instance, Double.parseDouble(value.replaceAll(",", "")));
		} catch (Exception e) {
			LOGGER.info("调用set函数出现错误：" + e.getLocalizedMessage());
		}
	}
	
	public static Double invokePropertyGetter(Object instance, int index) {
		try {
			Method getter = instance.getClass().getDeclaredMethod("getIndex" + index);
			return (Double)getter.invoke(instance);
		} catch (Exception e) {
			LOGGER.info("调用get函数出现错误：" + e.getLocalizedMessage());
			return null;
		}
	}
	
	public static double[] getAllValidData(Object instance, int size) {
		Double[] tempCache = new Double[size];
		for (int i=0; i<size; i++) {
			Double value = invokePropertyGetter(instance, i+1);
			if (value != null) tempCache[i] = value;
		}
		
		int lastValueIndex = tempCache.length - 1;
		while (lastValueIndex >= 0) {
			if (tempCache[lastValueIndex] != null) break;
			lastValueIndex--;
		}
		
		double[] result = new double[lastValueIndex + 1];
		for (int i=0; i<result.length; i++)
			if (tempCache[i] != null) result[i] = tempCache[i];
		
		return result;
	}
}
